package com.geen.tuoke.network.interceptor

import com.geen.tuoke.network.utils.CacheUtil
import com.geen.tuoke.utils.EventCode
import com.geen.tuoke.utils.LogUtils
import com.google.gson.Gson
import com.seeway.wms.network.api.ApiResponse
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import java.nio.charset.Charset

/***
 * 全局token拦截器
 */
class TokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val originalResponse: Response = chain.proceed(request)
        val responseBody = originalResponse.body()
        val source = responseBody!!.source()
        source.request(Long.MAX_VALUE) // Buffer the entire body.
        val buffer = source.buffer
        var charset = UTF8
        val contentType = responseBody.contentType()
        if (contentType != null) {
            charset = contentType.charset(UTF8)
        }
        var bodyString: String? = null
        if (charset != null) {
            bodyString = buffer.clone().readString(charset)
        }
        try{
            val appResponse = Gson().fromJson(bodyString, ApiResponse::class.java)
            if (appResponse != null) {
                val errorCode = appResponse.code
                //token过期，直接退出登陆 让用户登陆
                if (errorCode == 401) {
                    EventBus.getDefault().post(EventCode.EVENT_TOKEN_ERROR)
                }
            }
        }catch (e:Exception){
        }
        return originalResponse
    }

    companion object {
        private val UTF8 = Charset.forName("UTF-8")
    }
}